<template>
  <div>
    <el-dialog :close-on-click-modal="false" width="800px" :title="title" :visible.sync="dialogVisible">
      <el-form ref="form" v-loading="loading" :model="form" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="全局唯一, 对应前端路由中name" />
        </el-form-item>

        <el-form-item label="权限" prop="permissionCode">
          <el-button style="margin-right: 10px" size="small" @click="handleSelectPerm">选择权限</el-button>
          <el-tag v-for="name in form.permNames" :key="name" style="margin-right: 10px">{{ name }}</el-tag>
          <span v-if="form.permNames && form.permNames.length > 1">
            <span v-if="!form.needAllPerms" style="color: #409EFF">要求拥有其一</span>
            <span v-else="form.needAllPerms" style="color: #67C23A">要求全部具备</span>
          </span>
        </el-form-item>

        <el-form-item label="父级" prop="parentIds">
          <el-cascader
            v-model="parentIds"
            clearable
            style="width: 640px"
            :props="{ checkStrictly: true }"
            placeholder="根节点"
            :options="parents"
            @change="handleParentIdChange"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="2">目录</el-radio>
            <el-radio :label="0">页面</el-radio>
            <el-radio :label="1">子路由</el-radio>
          </el-radio-group>

        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标" />
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>

        <el-form-item label="启用" prop="description">
          <el-switch
            v-model="form.enabled"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="hide">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <perm-dialog ref="permDialog" :scope="scope" />
  </div>
</template>

<script>
import { getMenuInfo, updateMenu, addMenu } from '@/api/menu'
import { transToOptions, menusTreeToList, findParent } from '@/utils/menusUtil'
import PermDialog from './PermDialog'

export default {
  components: { PermDialog },
  props: {
    scope: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      title: '',
      mode: '',
      loading: false,
      dialogVisible: false,
      menuId: null,
      reject: null,
      resolve: null,
      parents: [],
      rules: {
        code: [{
          required: true,
          message: '请输入资源编码',
          trigger: 'blur'
        }
        ],
        type: [{
          required: true,
          message: '请输入资源类型',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'blur'
        }
        ],
        name: [{
          required: true,
          message: '请输入资源名称',
          trigger: 'blur'
        },
        {
          min: 2,
          max: 20,
          message: '长度在 2 到 20 个字符',
          trigger: 'blur'
        }
        ],
        uri: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ],
        method: [{
          required: true,
          message: '请输入资源请求类型',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ],
        description: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 20,
          message: '长度在 3 到 20 个字符',
          trigger: 'blur'
        }
        ]
      },
      form: {},
      parentIds: []
    }
  },
  mounted() {
    this.form = this.defaultForm()
  },

  methods: {
    defaultForm() {
      return {
        code: undefined,
        title: undefined,
        parentId: undefined,
        href: undefined,
        icon: '',
        type: 0,
        orderNum: 10,
        permNames: [],
        permList: [],
        needAllPerms: false,
        flag: undefined,
        description: undefined,
        visibility: undefined,
        path: undefined,
        enabled: 1
      }
    },

    fetchData() {
      this.loading = true
      return getMenuInfo(this.menuId, this.scope).then((res) => {
        this.loading = false
        if (res.code === 0) {
          this.form = res.data
        } else {
          this.$message.error(res.msg)
        }
        return res
      }).catch((error) => {
        console.error('getMenuInfo error', error)
        this.loading = false
      })
    },

    openAdd(parentId, treeData) {
      this.mode = 'add'
      this.title = '新增菜单'
      this.menuId = null
      this.form = this.defaultForm()
      this.form.parentId = parentId
      this.transformTree(treeData)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    openEdit(menuId, treeData) {
      this.title = '编辑菜单'
      this.menuId = menuId
      this.mode = 'edit'
      this.fetchData().then(() => {
        this.transformTree(treeData)
      })
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.dialogVisible = false
      this.form = this.defaultForm()
    },

    transformTree(treeData) {
      const parents = transToOptions(treeData, this.menuId)
      if (this.form.parentId) {
        const mList = menusTreeToList(parents)
        const ps = findParent(mList, this.form.parentId)
        const parentIds = []
        for (let i = 0; i < ps.length; i++) {
          parentIds.push(ps[i].id)
        }
        this.parentIds = parentIds
      } else {
        this.parentIds = []
      }
      this.parents = parents
    },

    handleParentIdChange(value) {
      if (value && value.length > 0) {
        this.form.parentId = value[value.length - 1]
      } else {
        this.form.parentId = -1
      }
    },
    handleSelectPerm() {
      this.$refs.permDialog.open(this.form.permList, this.form.needAllPerms).then((result) => {
        this.$set(this.form, 'permList', result.permList)
        this.$set(this.form, 'permNames', result.permNames)
        this.$set(this.form, 'needAllPerms', result.needAllPerms)
      })
    },
    updateMenu() {
      return updateMenu(this.form.id, this.form, this.scope).then((res) => {
        if (res.code === 0) {
          this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
          this.hide()
          this.resolve && this.resolve()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    addMenu() {
      if (!this.form.parentId) {
        this.form.parentId = -1
      }
      return addMenu(this.form, this.scope).then((res) => {
        if (res.code === 0) {
          this.$notify({ title: '成功', message: '添加成功', type: 'success', duration: 2000 })
          this.resolve && this.resolve()
          this.hide()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleSubmit() {
      if (this.mode === 'edit') {
        this.updateMenu()
      } else {
        this.addMenu()
      }
    }
  }
}
</script>
